{
 "nbformat": 4,
 "nbformat_minor": 2,
 "metadata": {
  "language_info": {
   "name": "python",
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   }
  },
  "orig_nbformat": 2,
  "file_extension": ".py",
  "mimetype": "text/x-python",
  "name": "python",
  "npconvert_exporter": "python",
  "pygments_lexer": "ipython3",
  "version": 3
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "编辑距离算法被数据科学家广泛应用，是用作机器翻译和语音识别评价标准的基本算法。\n",
    "\n",
    "最直观的方法是暴力检查所有可能的编辑方法，取最短的一个。所有可能的编辑方法达到指数级，但我们不需要进行这么多计算，因为我们只需要找到距离最短的序列而不是所有可能的序列。\n",
    "\n",
    "作者：LeetCode-Solution\n",
    "链接：https://leetcode-cn.com/problems/edit-distance/solution/bian-ji-ju-chi-by-leetcode-solution/\n",
    "来源：力扣（LeetCode）\n",
    "著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "举例\n",
    "\n",
    "**HOR**SE 和 **RO**S\n",
    "\n",
    "`dp[i-1][j]` 是比较的  HO 和 RO\n",
    "\n",
    "`dp[i][j-1]` 是比较的 HOR 和 R\n",
    "\n",
    "`dp[i-1][j-1]` 是比较的 HO和 R\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "定义`dp[i][j]`, 表示位置i,j位置需要变化的最短次数\n",
    "\n",
    "初始化：\n",
    "\n",
    "dp[i][0] = i\n",
    "\n",
    "dp[0][j] = j\n",
    "\n",
    "状态转移方程：\n",
    "\n",
    "如果`dp[i] == dp[j]` ,`dp[i][j]=dp[i-1][j-1]`\n",
    "\n",
    "不然 `dp[i][j] = max(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "|   |   | r | o | s |\n",
    "| - | - | - | - | - |\n",
    "|   | 0 | 1 | 2 | 3 |\n",
    "| h | 1 | 1 | 2 | 3 |\n",
    "| o | 2 | 2 | 1 | 2 |\n",
    "| r | 3 | 3 | 2 | 2 |\n",
    "| s | 4 | 4 | 3 | 2 |\n",
    "| e | 5 | 5 | 4 | 3 |"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Solution(object):\n",
    "    def minDistance(self, word1, word2):\n",
    "        \"\"\"\n",
    "        :type word1: str\n",
    "        :type word2: str\n",
    "        :rtype: int\n",
    "        \"\"\"\n",
    "        n1, n2 = len(word1), len(word2)\n",
    "        dp1 = [0] * (n2 + 1) #保留两行\n",
    "        dp2 = [0] * (n2 + 1)\n",
    "        dp1[0] = 0\n",
    "        for j in range(1, n2 + 1):\n",
    "            dp1[j] = j\n",
    "        for i in range(1, n1 + 1):\n",
    "            dp2[0] = i\n",
    "            for j in range(1, n2 + 1):\n",
    "                if word1[i - 1] == word2[j - 1]:\n",
    "                    dp2[j] = dp1[j - 1]\n",
    "                else:\n",
    "                    dp2[j] = min(dp1[j], dp2[j - 1], dp1[j - 1]) + 1\n",
    "            dp1, dp2 = dp2, dp1\n",
    "        return dp1[n2]"
   ]
  }
 ]
}